<?php

class ActiveRecord extends ActiveRecordBase
{
	var $seo_object_type = null;
	var $seo_name_field = '';

	public function init() {
		$class = get_class($this);
		$seo_object_type = strtoupper($class[0]);

		$this->seo_object_type = $seo_object_type;
		$this->seo_name_field = $class;

		parent::init();
	}

	// save seo
	public function afterSave() {
		if ( !isset($this->seo) ) {
			$this->seo = new Seo;
		}

		$this->seo->attributes = getPost('Seo');
		if ( empty($this->seo->seo_name) ) {
			$this->seo->seo_name = SiteHelper::generateSeoName($this->getAttribute($this->seo_name_field));
		}
		$this->seo->object_id = $this->primaryKey;
		$this->seo->object_type = $this->seo_object_type;
		
		$criteria = new CDbCriteria();
		$criteria->addCondition("seo_name=:name");
		$criteria->params[':name'] = $this->seo->seo_name;
		$ck = Seo::model()->findAll($criteria);
		if(empty($ck))
		$this->seo->save();
	}

	public function afterFind() {
		if ( !isset($this->seo) ) {
			$this->seo = new Seo;
		}
	}

	/* SEO URL */

	private function getDefaultUrl($params = null, $action = 'view', $controller = null) {
		if ( $controller === null ) {
			$controller = get_class($this);
			$controller[0] = strtolower($controller[0]);
		}

		if ( $params === null ) {
			$params = $this->getDefaultUrlParams();
		}

		return Yii::app()->urlManager->createUrl($controller.'/'.$action, $params);
	}

    public function getUrl()
    {
        $controller = get_class($this);
        $controller[0] = strtolower($controller[0]);

		$params = $this->getDefaultUrlParams($controller);

        return $this->getDefaultUrl($params);
    }

	public function getDefaultUrlParams() {
		$params = array('id' => $this->primaryKey);
		if ( isset($this->seo) && isset($this->seo->seo_name) ) {
			$params['name'] = $this->seo->seo_name;
		}

		return $params;
	}

	public function Search($criteria, $params = array()) {
		$_params = array(
			'pagination'=>array(
				'pageSize' => Yii::app()->user->getState('pageSize', param('defaultPageSize')),
			),
			'criteria' => $criteria,
		);
		
		$_params = $_params + $params;
		
		return new CActiveDataProvider(get_class($this), $_params);
	}
}